package edu.pitt.dbmi.odie.gapp.gwt.client.navigator;

import java.util.ArrayList;
import java.util.Iterator;

import com.allen_sauer.gwt.log.client.Log;
import com.smartgwt.client.types.FormLayoutType;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.LinkItem;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;

public class ODIE_DocumentLinkManager {

	private ArrayList<LinkItem> links = new ArrayList<LinkItem>() ;
	
	private boolean isFirstRowLink = true ;
	
	public ODIE_DocumentLinkManager() {
		;
	}
	
	public DynamicForm buildForm(DynamicForm form) {
		return buildFormFromLinkItems(form, this.links) ;
	}
	
	protected DynamicForm buildFormFromLinkItems(DynamicForm form, ArrayList<LinkItem> linkItems) {
		if (linkItems.size() > 0) {
			form.setCellBorder(0) ;
			form.setCellPadding(0) ;
			form.setCellSpacing(0) ;
			form.setMinColWidth(1) ;
			form.setFixedColWidths(true) ;
			form.setTitleWidth(0) ;
			form.setItemLayout(FormLayoutType.TABLE);
			form.setNumCols(80);
			final LinkItem[] linkItemArray = new LinkItem[linkItems.size()];
			int ldx = 0;
			for (LinkItem linkItem : linkItems) {
				linkItemArray[ldx++] = linkItem;
			}
			form.setFields(linkItemArray);
		}
		return form;
	}
	
	public void newRow() {
		isFirstRowLink = true ;
	}
	
	public LinkItem addLinkItem(ArrayList<Character> htmlBuffer, String styleName) {
		String result = "";
		for (Iterator<Character> resultIterator = htmlBuffer.iterator(); resultIterator
				.hasNext();) {
			result += resultIterator.next();
		}
		return addLinkItem(result, styleName) ;
	}
	
	public LinkItem addClickableLinkItem(ArrayList<Character> htmlBuffer,
			String constAnnotationTextStyle, ClickHandler clickHandler) {
		LinkItem linkItem = addLinkItem(htmlBuffer, constAnnotationTextStyle) ;
		linkItem.addClickHandler(clickHandler) ;
		return linkItem ;
	}
	
	public LinkItem addLinkItem(String htmlValue, String styleName) {
		LinkItem linkItem = new LinkItem();
		linkItem.setValue(htmlValue);
		linkItem.setTitle("") ;
		linkItem.setShowTitle(false);
		int currentLineCharacters = calculateAbsoluteCharacters(htmlValue) ;
		Log.debug("Setting columnSpan of " + currentLineCharacters + " for '" + htmlValue + "'") ;
		linkItem.setColSpan(currentLineCharacters);
		linkItem.setWidth(currentLineCharacters) ;
		linkItem.setTextBoxStyle(styleName);
		if (isFirstRowLink) {
			linkItem.setStartRow(true) ;
			isFirstRowLink = false;
		}
		links.add(linkItem) ;
		return linkItem ;
	}
	
	protected int calculateAbsoluteCharacters(String htmlValue) {
		String reducedValue = htmlValue.replace("&nbsp;", " ") ;
		return reducedValue.length() ;
	}
	


}
